package com.cuanbo.dualscreenteachzhu.utils;

import android.text.TextUtils;

import com.cuanbo.dualscreenteachzhu.base.App;
import com.cuanbo.dualscreenteachzhu.listener.HttpListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *Http请求工具类
 */
public class HttpClient {

    /**
     * http get请求
     * @param httpurl http地址
     * @return 请求成功后返回响应结果
     */
    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            LogUtil.addError("----------Http Get请求异常-----------");
            LogUtil.addError("请求地址:" + httpurl);
            LogUtil.addError(e);
            LogUtil.addError("-------------------------------------");
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                connection.disconnect();// 关闭远程连接
            }
        }

        return result;
    }

    /**
     *http post请求，该返回会创建独立的线程去做Http请求
     * @param urlPath 请求地址
     * @param json 要携带的json字符串格式的数据
     * @param httpListener 请求结果是否成功的回调接口
     * @param fileName 日志tag的名称
     */
    public static void doPostInNewThread(final String urlPath, final String json, final HttpListener httpListener, final String fileName) {
        if (!App.serverIPNetState) {
            if (httpListener != null) {
                httpListener.fail();
            }
            return;
        }
        if (!urlPath.contains("http")) {
            if (App.configInfo == null || TextUtils.isEmpty(App.configInfo.getServerIP())) {
                LogUtil.add("doPost", "配置文件或者服务器IP为空！", fileName, false);
                if (httpListener != null) {
                    httpListener.fail();
                }
                return;
            }
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                // HttpClient 6.0被抛弃了
                String result = null;
                BufferedReader reader = null;
                HttpURLConnection conn = null;
                try {
                    URL url = null;
                    if (urlPath.contains("http")) {
                        url = new URL(urlPath);
                        LogUtil.add("请求地址", urlPath, fileName, false);
                    } else {
                        url = new URL(App.configInfo.getServerIP() + urlPath);
                        LogUtil.add("请求地址", App.configInfo.getServerIP() + urlPath, fileName, false);
                    }
                    LogUtil.add("请求参数", json, fileName, false);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    // 设置文件类型:
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    // 设置接收类型否则返回415错误
                    //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
                    conn.setRequestProperty("accept", "application/json");
                    // 往服务器里面发送数据
                    if (json != null && !TextUtils.isEmpty(json)) {
                        byte[] writebytes = json.getBytes();
                        // 设置文件长度
                        conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                        OutputStream outwritestream = conn.getOutputStream();
                        outwritestream.write(json.getBytes());
                        outwritestream.flush();
                        outwritestream.close();
                    }
                    LogUtil.add("响应码", "" + conn.getResponseCode(), fileName, false);
                    if (conn.getResponseCode() == 200) {
                        reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));
                        result = reader.readLine();
                        LogUtil.add("请求成功", result, fileName, false);
                        if (httpListener != null) {
                            httpListener.success(result);
                        };
                    } else {
                        if (httpListener != null) {
                            httpListener.fail();
                        }
                    }
                } catch (Exception e) {
                    if (httpListener != null) {
                        httpListener.fail();
                    }
                    LogUtil.addError("urlPath=" + urlPath);
                    LogUtil.addError("json=" + json);
                    LogUtil.addError(e);
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {}
                    }
                    if(conn!=null){
                        try{
                            conn.disconnect();
                        }catch (Exception e){}
                    }
                }
            }
        }).start();
    }

    /**
     *http post请求
     * @param urlPath 请求地址
     * @param json 要携带的json字符串格式的数据
     * @param httpListener 请求结果是否成功的回调接口
     * @param fileName 日志tag的名称
     */
    public static void doPost(final String urlPath, final String json, final HttpListener httpListener, final String fileName) {
        if (!App.serverIPNetState) {
            if (httpListener != null) {
                httpListener.fail();
            }
            return;
        }

        if (!urlPath.contains("http")) {
            if (App.configInfo == null || TextUtils.isEmpty(App.configInfo.getServerIP())) {
                LogUtil.add("doPost", "配置文件或者服务器IP为空！", fileName, false);
                if (httpListener != null) {
                    httpListener.fail();
                }
                return;
            }
        }

        // HttpClient 6.0被抛弃了
        String result = null;
        HttpURLConnection conn=null;
        BufferedReader reader = null;
        try {
            URL url = null;
            if (urlPath.contains("http")) {
                url = new URL(urlPath);
                LogUtil.add("请求地址", urlPath, fileName, false);
            } else {
                url = new URL(App.configInfo.getServerIP() + urlPath);
                LogUtil.add("请求地址", App.configInfo.getServerIP() + urlPath, fileName, false);
            }

            LogUtil.add("请求参数", json, fileName, false);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept", "application/json");
            // 往服务器里面发送数据
            if (json != null && !TextUtils.isEmpty(json)) {
                byte[] writebytes = json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(json.getBytes());
                outwritestream.flush();
                outwritestream.close();
            }
            LogUtil.add("响应码", "" + conn.getResponseCode(), fileName, false);
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
                LogUtil.add("请求成功", result, fileName, false);
                if (httpListener != null) {
                    httpListener.success(result);
                }
            } else {
                if (httpListener != null) {
                    httpListener.fail();
                }
            }
        } catch (Exception e) {
            if (httpListener != null) {
                httpListener.fail();
            }
            LogUtil.addError("urlPath=" + urlPath);
            LogUtil.addError("json=" + json);
            LogUtil.addError(e);
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    LogUtil.addError("urlPath=" + urlPath);
                    LogUtil.addError("json=" + json);
                    LogUtil.addError(e);
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try{
                    conn.disconnect();
                }catch (Exception e){}
            }
        }
    }

}
